package main;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import utils.DateUtility;
import utils.ImageUtil;
import utils.SystemParm;

import java.util.logging.*;

public class MovePic {

	private Logger logger = Logger.getLogger("picMove");
	private Connection conn;

	/**
	 * 创建数据库连接
	 * 
	 * @throws IOException
	 */
	public MovePic(String filePath) throws IOException {
		FileHandler fileHandler = new FileHandler("D:\\MovePic.log", true);
		fileHandler.setLevel(Level.INFO);
		fileHandler.setFormatter(new SimpleFormatter());
		logger.addHandler(fileHandler);

		logger.info("-----------------------");

		SystemParm.load(filePath);

		String url = SystemParm.getParm("db_url");
		String user = SystemParm.getParm("db_user");
		String password = SystemParm.getParm("db_password");
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			System.out.println("连接成功！");
		} catch (ClassNotFoundException e) {
			System.out.println("MySQL JDBC 驱动未找到！");
			e.printStackTrace();
		} catch (SQLException e) {
			System.out.println("数据库连接失败！");
			e.printStackTrace();
		} catch (Exception e) {
			e.getMessage();
		}

	}

	/**
	 * 遍历源文件夹
	 * 
	 * @throws IOException
	 * @throws SQLException
	 */
	public void sourFile() throws IOException, SQLException {

		File folder = new File(SystemParm.getSourcePath());// 源文件夹路径
		File[] listOfFiles = folder.listFiles();
		logger.info("此次压缩的总图片数量为 : " + listOfFiles.length);
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		for (int i = 0; i < listOfFiles.length; i++) {
			if (listOfFiles[i].isFile()) {
				try {
					// 复制平面图片
					String barcode = listOfFiles[i].getName().substring(0, listOfFiles[i].getName().indexOf("."));
					logger.info("复制完成-----------" + barcode);
					map = (HashMap<String, Integer>) getTimeInfo(barcode); // 获取到年份季度

					// 压缩图片(生成小图)
					compressImg(map.get("yearId"), map.get("quarterId"), map.get("productBardoctId"), barcode);
					logger.info("压缩完成-----------" + barcode);

					// 备份图片
					String source = SystemParm.getSourcePath() + "\\" + listOfFiles[i].getName();
					String dest = SystemParm.getBackupPicPath() + "\\" + listOfFiles[i].getName();
					copyFileUsingStream(source, dest);
					logger.info("备份完成-----------" + barcode);

					// 备份完成后删除源文件夹下面的文件
					listOfFiles[i].delete();
					logger.info(listOfFiles[i].getName());
					logger.info("此次压缩的总图片数量为：--" + listOfFiles.length + "---目前已完成：----" + (i + 1));

				} catch (Exception e) {
					System.out.println(e);
					error(e);
					logger.severe(listOfFiles[i].getName() + " / " + e.getMessage());
				}
			}
		}
	}

	private void error(Exception e) {
		StackTraceElement[] eles = e.getStackTrace();
		logger.severe(e.getMessage());
		for (StackTraceElement ele : eles)
			logger.severe(ele.toString());
	}

	/**
	 * 复制文件
	 * 
	 * @param source
	 * @param dest
	 * @throws IOException
	 */
	private void copyFileUsingStream(String source, String dest) throws IOException {
		// 指定源文件和目标文件的路径
		Path sourcePath = Paths.get(source);
		Path destinationPath = Paths.get(dest);

		File file = new File(dest);
		file.mkdirs();

		try {
			// 使用Files.copy拷贝文件
			Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
		} catch (IOException e) {
			error(e);
			logger.severe("File copying failed, " + source + "," + dest + "," + e.getMessage());
		}

	}

	/**
	 * 压缩图片
	 * 
	 * @throws IOException
	 * @throws SQLException
	 */
	public void compressImg(int year, int quarter, int productBarcodeId, String barcode)
			throws IOException, SQLException {
		// 小图文件夹名称
		String smallPhoneFileName = SystemParm.getPicPath() + year + "\\" + quarter + "\\" + barcode + "\\" + barcode
				+ "_" + 1 + "s" + ".jpg";
		// 在指定路径中创建一个文件(该文件是空的)
		File fileS = new File(smallPhoneFileName);
		fileS.setWritable(true, false);
		String sourceFile = SystemParm.getSourcePath() + "\\" + barcode + ".jpg";
		;
		// 复制一份
		copyFileUsingStream(sourceFile, smallPhoneFileName);

		int widthS = ImageUtil.getPicWidth(fileS);
		int heightS = ImageUtil.getPicHeight(fileS);
		double ratioS = (double) widthS / (double) heightS;
		System.out.println("Width : " + widthS + " Height : " + heightS + "Ratio : " + ratioS);

		BufferedImage srcImageS = ImageIO.read(fileS);
		BufferedImage largeImageS = ImageUtil.resizeImage(srcImageS, 100, (int) (100 / ratioS));
		// 图像缓冲区图片保存为图片文件(文件不存在会自动创建文件保存，文件存在会覆盖原文件保存)
		ImageIO.write(largeImageS, "jpg", fileS);

		// 补充小图路径
		String updatePic = "UPDATE product_barcode_pic SET pic_s_path = ?  WHERE pb_id = ?;";
		PreparedStatement updateStatement = conn.prepareStatement(updatePic);

		String picsPath = "\\" + year + "\\" + quarter + "\\" + barcode + "\\" + barcode + "_1s" + ".jpg";
		updateStatement.setString(1, picsPath);
		updateStatement.setInt(2, productBarcodeId);
		updateStatement.executeUpdate();

	}

	/**
	 * 查询条码年份季度信息
	 * 
	 * @param barcode
	 * @throws SQLException
	 * @throws IOException
	 */
	public Map<String, Integer> getTimeInfo(String barcode) throws SQLException, IOException {
		// 图片类型(1.平面图，2.手机图，5.模特图一，6.模特图二)
		int type = 1;

		Map<String, Integer> map = new HashMap<String, Integer>();
		// 查询年份季度
		String getInfo = "SELECT s2.year_ID,s2.quarter_ID FROM product_barcode s1 INNER JOIN  product s2 ON s1.product_id = s2.product_ID WHERE s1.barcode = ?;";
		PreparedStatement pstmt = conn.prepareStatement(getInfo);

		pstmt.setString(1, barcode);
		ResultSet results = pstmt.executeQuery();
		while (results.next()) {
			Integer yearId = results.getInt("year_ID");
			Integer quarterId = results.getInt("quarter_ID");
			Integer pbId = getProductBarcodePic(barcode, type);

			Integer productBarcodeId = getProductBarcodeId(barcode);

			if (yearId != null && quarterId != null) {
				// 源文件
				String source = SystemParm.getSourcePath() + "\\" + barcode + ".jpg";
				// 路径文件夹
//	        	String destFile = SystemParm.getPicPath() + "\\"+ yearId + "\\" + quarterId + "\\" + barcode;
//	        	File file = new File(destFile);
//	        	file.mkdirs();
				// 平面图文件
				String dest = SystemParm.getPicPath() + "\\" + yearId + "\\" + quarterId + "\\" + barcode + "\\"
						+ barcode + "_1" + ".jpg";
				copyFileUsingStream(source, dest);

				if (pbId == null) {
					// productBarcodePic添加信息
					String insertPic = "INSERT product_barcode_pic(pb_id,type,pic_path,create_time,last_update_time,barcode) VALUES(?,?,?,?,?,?);";
					PreparedStatement inserStatement = conn.prepareStatement(insertPic);

					inserStatement.setInt(1, productBarcodeId);
					inserStatement.setInt(2, type);
					String picPath = "\\" + yearId + "\\" + quarterId + "\\" + barcode + "\\" + barcode + "_1" + ".jpg";
					inserStatement.setString(3, picPath);
					inserStatement.setTimestamp(4, DateUtility.getToday());
					inserStatement.setTimestamp(5, DateUtility.getToday());
					inserStatement.setString(6, barcode);
					inserStatement.executeUpdate();
				} else {
					// 修改最后一次修改时间
					String updatePic = "UPDATE product_barcode_pic SET last_update_time = ?  WHERE pb_id = ?;";
					PreparedStatement updateStatement = conn.prepareStatement(updatePic);

					updateStatement.setTimestamp(1, DateUtility.getToday());
					updateStatement.setInt(2, productBarcodeId);
					updateStatement.executeUpdate();
				}

				map.put("yearId", yearId);
				map.put("quarterId", quarterId);
				map.put("productBardoctId", productBarcodeId);
			} else {
				logger.severe("无法获取年份和季度 : " + yearId + ", " + quarterId);
			}

		}

		pstmt.close();
		return map;

	}

	/**
	 * 根据条码查找productBarcodeId
	 * 
	 * @param barcode
	 * @return
	 * @throws SQLException
	 */
	public Integer getProductBarcodeId(String barcode) throws SQLException {
		String getInfo = "SELECT id FROM product_barcode WHERE barcode = ?";
		PreparedStatement pstmt = conn.prepareStatement(getInfo);

		pstmt.setString(1, barcode);
		ResultSet results = pstmt.executeQuery();
		while (results.next()) {
			Integer productBarcodeId = results.getInt("id");
			return productBarcodeId;
		}
		return null;
	}

	/**
	 * 根据条码查找图片路径记录是否存在
	 * 
	 * @param barcode
	 * @return
	 * @throws SQLException
	 */
	public Integer getProductBarcodePic(String barcode, int type) throws SQLException {
		String picInfo = "SELECT pb_id FROM product_barcode_pic WHERE barcode = ? and type=?;";
		PreparedStatement picStm = conn.prepareStatement(picInfo);

		picStm.setString(1, barcode);
		picStm.setInt(2, type);
		ResultSet results = picStm.executeQuery();
		while (results.next()) {
			Integer productBarcodeId = results.getInt("pb_id");
			return productBarcodeId;
		}
		return null;
	}

	/**
	 * 日志记录
	 * 
	 * @param content  内容
	 * @param filePath 文件路径
	 * @return
	 */
	public void writeReport(String content) {
		logger.info(content);
	}

	/**
	 * 主程序入口
	 * 
	 * @param args
	 * @throws IOException
	 * @throws SQLException
	 */
	public static void main(String[] args) throws IOException, SQLException {
		MovePic movePic = new MovePic(args[0]);
		movePic.sourFile();
	}

}
